package com.baixun.service.impl;

import com.baixun.constant.MessageConstant;
import com.baixun.entity.PageResult;
import com.baixun.entity.QueryPageBean;
import com.baixun.mapper.UserMapper;
import com.baixun.mapper.UserDepMapper;
import com.baixun.pojo.Dep;
import com.baixun.pojo.User;
import com.baixun.pojo.UserDep;
import com.baixun.service.UserService;
import com.baixun.utils.MD5;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

@Service
@Transactional
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserDepMapper userDepMapper;


    /**
     * 条件分页查询
     *
     * @param
     * @return
     */
    @Override
    public PageResult findUserByConditionAndPage(QueryPageBean<User> queryPageBean) {

        Integer currentPage = queryPageBean.getCurrentPage();
        Integer pageSize = queryPageBean.getPageSize();
        User user = queryPageBean.getQuery();

        PageHelper.startPage(currentPage, pageSize);
        Page<User> page = userMapper.findUserByCondtion(user);
        return new PageResult(page.getTotal(), page.getResult());
    }

    /**
     * 新增用户
     *
     * @param user
     */
    @Override
    public void addUser(User user) {

        //密码使用md5+盐来加密
        if (user.getPassword() != null && !"".equals(user.getPassword().trim())) {
            String s = user.getLoginName() + user.getPassword();
            String password = MD5.formatMD5(s);
            user.setPassword(password);
        }
        //添加用户信息,先判断添加的手机号以及登录名是否已经存在
        List<User> tempUsers = userMapper.findUserByLoinUsernameorPhone(user);
        if (tempUsers != null && tempUsers.size() > 0) {
            throw new RuntimeException("登录名或手机号已存在");
        }
        //添加用户以及指定用户的角色，不指定默认为空
        userMapper.alter_auto_increment();
        userMapper.addUser(user);

    }


    /**
     * 根据id更新用户
     *
     * @param user
     */
    @Override
    public void updateUserById(User user) {

        //密码使用md5+盐来加密
        if (user.getPassword() != null && !"".equals(user.getPassword().trim())) {
            String s = user.getLoginName() + user.getPassword();
            String password = MD5.formatMD5(s);
            user.setPassword(password);
        }

        //判断登录名或手机号是否已经存在
        List<User> tempUsers = userMapper.findUserByLoinUsernameorPhone(user);
        if (tempUsers != null && tempUsers.size() > 0) {
            throw new RuntimeException("登录名或手机号已存在");
        }
        //根据id查询数据，乐观锁
        User tempUser = userMapper.findUserById(user.getId());
        user.setVersion(tempUser.getVersion());
        userMapper.updateUser(user);
    }

    /**
     * 永久删除用户,需要先判断删除的用户是否已经加入部门
     * 如果加入部门，删除失败，提示已经加入部门，需要先从部门移除用户
     * @param id
     */
    @Override
    public void deleteById(Integer id) {

        //判断user_dep表中是否有此用户信息，没有则删除
        List<UserDep> list = userDepMapper.findUserByUserId(id);
        if(list != null && list.size() > 0){
            throw new RuntimeException("部门中有此用户，请先从部门移除");
        }
        //删除用户表
        userMapper.deleteById(id);
    }

    //暂时删除用户
    @Override
    public void tempDeleteUser(Integer id, Byte status) {

        HashMap<String, Object> map = new HashMap<>();
        map.put("id", id);
        map.put("status", status);
        userMapper.tempDelete(map);
    }

    /**
     * 根据用户id查询用户
     *
     * @param id
     * @return
     */
    @Override
    public User findUserById(Integer id) {

        return userMapper.findUserById(id);
    }

    /**
     * 根据条件查询用户
     *
     * @param user
     * @return
     */
    @Override
    public User findByCondition(User user) {

        if (user != null) {

            String loginName = user.getLoginName();
            String phone = user.getPhone();


            QueryWrapper<User> wrapper = new QueryWrapper<>();
            if (loginName != null && loginName.trim().length() > 0) {
                wrapper.eq("login_name", loginName);
            }
            if (phone != null && phone.trim().length() > 0) {
                wrapper.eq("phone", phone);
            }
            user = userMapper.selectOne(wrapper);
            return user;

        } else {
            throw new RuntimeException("查询条件为空");
        }
    }

    /**
     * 登录
     *
     * @param loginName
     * @param password
     * @return
     */
    @Override
    public User login(String loginName, String password) {


        User user = userMapper.findUserByloginName(loginName);
        if (user == null) {
            throw new RuntimeException(MessageConstant.LOING_NAME_NOTEXIST);
        }
        String login_password = MD5.formatMD5(loginName + password);
        if (user.getPassword().equals(login_password)) {
            //修改登录时间
            UpdateWrapper<User> wrapper = new UpdateWrapper<>();
            wrapper.set("login_time",new Date()).eq("id",user.getId());
            userMapper.update(user,wrapper);
            return user;
        } else {
            return null;
        }
    }

}
